package com.open.capacity.user.service.impl;

import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.entity.SysInvoice;
import com.open.capacity.reimburse.service.SysInvoiceService;
import com.open.capacity.user.dao.SysFileDao;
import com.open.capacity.user.model.SysFile;
import com.open.capacity.user.service.SysFileService;
import com.open.capacity.utils.SysUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class SysFileServiceImpl implements SysFileService {

    @Autowired
    private SysFileDao fileDao;

    @Autowired
    private SysInvoiceService invoiceService;

    /**
     * 添加
     *
     * @param file
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(SysFile file) {
        SysUser user = SysUserUtil.getLoginAppUser();
        file.setUpdateUserid(user.getId());
        file.setUpdateUsername(user.getRealName());
        file.setUpdateTime(new Date());

        //发票拷贝一份
        if (file.getIsInvoice() != null && file.getIsInvoice().equals(1)) {
            SysInvoice invoice = new SysInvoice();
            invoice.setId(file.getId());
            invoice.setProcessId(file.getProcessId());
            invoice.setName(file.getName());
            invoice.setUrl(file.getUrl());
            invoice.setExt(file.getExt());
            invoice.setCreateTime(new Date());
            invoice.setCreateUserid(user.getId());
            invoice.setCreateUsername(user.getRealName());
            invoiceService.save(invoice);
        }

        return fileDao.save(file);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveFiles(SysFile[] files, String folderId) {
        if (files != null && files.length > 0) {
            fileDao.deleteByFolderId(files[0].getFolderId());
            for (SysFile file : files) {
                save(file);
            }
        }
        return 1;
    }

    @Override
    public int updateStatus(String id, Integer status) {
        return fileDao.updateStatus(id,status);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return fileDao.delete(id);
    }

    @Override
    public int deleteByFolderId(String folderId) {
        return fileDao.deleteByFolderId(folderId);
    }


    @Override
    public List<SysFile> findByFolderId(String folderId) {
        return fileDao.findByFolderId(folderId);
    }

    @Override
    public SysFile findById(String id) {
        return fileDao.findById(id);
    }

}
